import React, { Component } from 'react'
import { Button, Form, Input, Space, InputNumber, Tooltip, message, Modal } from 'antd'
import { QuestionCircleOutlined } from "@ant-design/icons";
import TheTable from '@/components/TheTable'
import TheButton from '@/components/TheButton'
import _ from 'lodash'
import '../style/style.less'
import {
    apiPetCheckManagePageOne,
    apiPetCheckManagePageTwo,
    apiPetCheckManagePageAdd,
    apiPetCheckManagePageUpdate,
    apiPetCheckManagePageDel
} from '@/request/petDistinguish/vdo';

class Category extends Component {
    constructor(props) {
        super(props)
        this.FormRef = React.createRef();
        this.state = {
            form_show: false,
            columns1: [
                {
                    title: '鉴别维度',
                    dataIndex: 'manageName',
                    key: 'manageName',
                },
                {
                    title: '排序',
                    dataIndex: 'manageSort',
                    key: 'manageSort',
                    filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
                    filterIcon: () => {
                        return (
                            <Tooltip placement="top" title={() => { return <div> APP报告一级维度展示顺序，数字越小越靠前</div> }}  >
                                <QuestionCircleOutlined style={{ fontSize: '20px' }} />
                            </Tooltip>
                        );
                    },
                    render: (text, record) => {
                        return text??'-'
                    }
                },
                {
                    title: '评分占比',
                    dataIndex: "scoreRatio",
                    key: "scoreRatio",
                    filterDropdown: true, // 自定义的列筛选功能，我们占位为信息提示Icon的位置
                    filterIcon: () => {
                        return (
                            <Tooltip placement="top" title={() => { return <div>每个一级维度评分占比综合需等于100%</div> }}  >
                                <QuestionCircleOutlined style={{ fontSize: '20px' }} />
                            </Tooltip>
                        );
                    },
                    render: (text, record) => {
                        if (record.canDelete){
                            return "-"
                        }
                        else {
                            return text +"%"
                        }
                    }
                },
                {
                    title: '操作',
                    width: 250,
                    render: (text, record) => {
                        return (
                            <>
                                <TheButton disabled={record.canDelete} onClick={(e) => this.addDialog(e, 2, record)}>
                                    增加二级维度
                                </TheButton>
                                <TheButton onClick={(e) => this.editDialog(e, 1, record)}>
                                    编辑
                                </TheButton>
                                <TheButton disabled={record.canDelete} onClick={(e) => this.delConfirm(e, record, '一')}>
                                    删除
                                </TheButton>
                            </>
                        )
                    },
                },
            ],
            columns2: [
                {
                    title: '二级维度',
                    dataIndex: 'manageName',
                    key: 'manageName',
                },
                {
                    title: '操作',
                    render: (text, record) => {
                        return (
                            <>
                                <TheButton haspermi={['petCircleUtil:category:edit2']} onClick={(e) => this.editDialog(e, 2, record)}>
                                    编辑
                                </TheButton>
                                <TheButton disabled={record.canDelete} haspermi={['petCircleUtil:category:delete2']} onClick={(e) => this.delConfirm(e, record, '二')}>
                                    删除
                                </TheButton>
                            </>
                        )
                    },
                },
            ],
            dataSource: {
                1: [], // 一级类目
                2: [], // 二级类目
            },
            manageType: props.type,
            visible: false, //新增修改弹窗
            title: '',
            level: 1, // 层级(初始层级1)
            manageId: '', // 类目id
            manageParentId: '',
            classID: '',
            queryForm: {},
            flag: false
        }
    }
    componentDidMount() {
        this.getData()
    }
    // 列表
    getData = async () => {
        let { level, manageType, dataSource } = this.state
        let params = {
            manageType,
        }
        console.log(level,dataSource)
        apiPetCheckManagePageOne(params).then(res=>{
            if (res.code === 0 && res.data){
                dataSource[level] = res.data
                this.setState({
                    dataSource
                })
            }
        })
    }
    // 点击一级类目显示对应的二级类目
    handleClick = (value) => {
        let { dataSource } = this.state
        if (value.manageLevel === 1){
            apiPetCheckManagePageTwo({
                manageParentId: value.manageId
            }).then(res=>{
                if (res.code === 0 && res.data){
                    dataSource[2] = res.data
                    this.setState({
                        dataSource,
                        manageId: value.manageId,
                        classID: value.manageId,
                    })
                }
            })
        }
    }
    // 点击表格切换类名
    setRowClassName = (record) => {
        const { manageLevel } = record
        if (manageLevel === 1) {
            return record.manageId === this.state.classID ? 'active-row' : ''
        }
    }
    // 新增类目
    addDialog = (e, level, value) => {
        e.stopPropagation()
        if (level === 1){
            this.setState({
                level, // 当前选择的类目级别
                title: '新增一级鉴别维度',
                visible: true,
            })
        }
        else{
            this.setState({
                level, // 当前选择的类目级别
                title: '新增二级鉴别维度',
                visible: true,
                levelName: value.manageName,
                manageId: value.manageId
            })
        }
    }
    // 修改类目
    editDialog = (e, level, value) => {
        e.stopPropagation()
        if (level === 1){
            this.setState({
                title: '编辑一级鉴别维度',
                visible: true,
                level,
                manageId: value.manageId,
                flag: !!value.canDelete
            }, () => {
                this.FormRef.current.setFieldsValue({
                    ...value
                })
            })
        }
        else{
            this.setState({
                level: level, // 当前选择的类目级别
                title: '编辑二级鉴别维度',
                visible: true,
                levelName: value.manageNameLevel1,
                manageId: value.manageId,
                manageParentId: value.manageParentId
            }, () => {
                this.FormRef.current.setFieldsValue({
                    ...value
                })
            })
        }
    }
    // 关闭弹窗
    closeDialog = () => {
        this.setState({
            title: '',
            visible: false,
            flag: false
        })
        this.FormRef.current.resetFields()
    }
    // 删除类目
    delConfirm = (e, value, str) => {
        let { manageLevel, manageId } = value
        e.stopPropagation()
        React.$confirm({
            title: `确认删除该维度吗？`,
            onOk: async () => {
                apiPetCheckManagePageDel({
                    manageId,
                }).then(res=>{
                    if (res.code === 0){
                        message.success('删除成功')
                        if (manageLevel === 1){
                            let { dataSource } = this.state
                            dataSource[2] = []
                            this.setState({
                                dataSource,
                                level: 1
                            },()=>{
                                this.getData()
                            })
                        }
                        else {
                            this.handleClick({
                                manageId: this.state.manageId,
                                manageLevel: 1
                            })
                        }
                    }
                })
            },
        })
    }
    // 保存新建/修改
    dialogSave = async (values) => {
        const { level, title, manageType, manageId, manageParentId } = this.state;
        let params = {
            ...values,
            manageType,
            manageLevel: level
        }
        if (title.includes('新增')) {
            if (level === 2){
                params.manageParentId = manageId
            }
            apiPetCheckManagePageAdd(params).then(res=>{
                if (res.code === 0){
                    this.closeDialog()
                    message.success('新增成功')
                    if (level === 2){
                        this.handleClick({
                            manageId: manageId,
                            manageLevel: 1,
                        })
                    }else {
                        this.getData()
                    }
                }
            })
        }
        else {
            params.manageId = manageId
            apiPetCheckManagePageUpdate(params).then(res=>{
                if (res.code === 0){
                    this.closeDialog()
                    message.success('修改成功')
                    if (level === 2){
                        this.handleClick({
                            manageId: manageParentId,
                            manageLevel: 1,
                        })
                    }else {
                        this.getData()
                    }
                }
            })
        }
    }

    render() {
        const { dataSource, visible, title, level, levelName,flag } = this.state
        return (
            <div className="p-layout-box">
                <div style={{ display: 'flex' }}>
                    <TheButton type="default" size="middle" onClick={(e) => this.addDialog(e, 1, '')}>
                        新增鉴别维度
                    </TheButton>
                </div>
                <div className="p-layout-content vd-category-second">
                    {_.map(dataSource, (v, i) => {
                        return (
                            <TheTable
                                onRow={(record, index) => {
                                    return {
                                        onClick: () => this.handleClick(record),
                                    }
                                }}
                                scroll={{ y: '75vh' }}
                                rowClassName={this.setRowClassName}
                                columns={this.state[`columns${i}`]}
                                dataSource={v}
                            />
                        )
                    })}
                </div>
                <Modal
                    width={500}
                    maskClosable={false}
                    visible={visible}
                    title={title}
                    footer={null}
                    onCancel={this.closeDialog}
                >
                    <Form
                        ref={this.FormRef}
                        onFinish={this.dialogSave}
                        labelCol={{ span: 7 }}
                    >
                        {(level === 1) && (
                            <>
                                <Form.Item
                                    name="manageName"
                                    label="名称"
                                    rules={[{ required: true }]}>
                                    <Input maxLength={8} placeholder="最多允许输入8个字" />
                                </Form.Item>
                                <Form.Item
                                    name="scoreRatio"
                                    label="评分占比"
                                    rules={[{ required: !flag }]}
                                >
                                    <InputNumber disabled={flag} min={0} max={100} addonAfter={'%'} precision={0} placeholder="输入0-100的整数"/>
                                </Form.Item>
                                <Form.Item
                                    name="manageSort"
                                    label="排序"
                                    rules={[{ required: !flag }]}
                                >
                                    <InputNumber disabled={flag} placeholder="请输入排序" min={1} max={9999} precision={0} />
                                </Form.Item>
                            </>
                        )}
                        {(level === 2) && (
                            <>
                                <Form.Item
                                    name="levelName"
                                    label="一级鉴别维度名称">
                                    <span className="ant-form-text">{levelName}</span>
                                </Form.Item>
                                <Form.Item
                                    name="manageName"
                                    label="二级鉴别维度名称"
                                    rules={[{ required: true }]}>
                                    <Input maxLength={8} placeholder="最多允许输入8个字" />
                                </Form.Item>
                            </>
                        )}

                        <Form.Item>
                            <div
                                style={{
                                    display: 'flex',
                                    justifyContent: 'flex-end',
                                    marginBottom: -30,
                                }}>
                                <Space>
                                    <Button onClick={this.closeDialog}>取消</Button>
                                    <Button type="primary" htmlType="submit">
                                        保存
                                    </Button>
                                </Space>
                            </div>
                        </Form.Item>
                    </Form>
                </Modal>
            </div>
        )
    }
}

export default Category
